package org.glassfish.jersey.examples.freemarker;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;

import java.util.*;

import javax.servlet.ReadListener;
import javax.servlet.http.HttpUtils;

import org.apache.commons.beanutils.BeanUtils;

import demo.jaxrs.server.Person;
 
 
@Provider
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class FormReader implements MessageBodyReader {
   
    public Object readFrom(Class arg0, Type arg1, Annotation[] arg2,
            MediaType arg3, MultivaluedMap arg4, final InputStream arg5)
            throws IOException, WebApplicationException {
         
        try {
         
            Object bean = arg0.newInstance();
     
            Object contentLength = arg4.getFirst("Content-Length");
             
            int length = Integer.parseInt( String.valueOf(contentLength));
 
            javax.servlet.ServletInputStream sin =
                new javax.servlet.ServletInputStream() {
                    @Override
                    public int read() throws IOException {
                        return arg5.read();
                    }

					@Override
					public boolean isFinished() {
						// TODO Auto-generated method stub
						return false;
					}

					@Override
					public boolean isReady() {
						// TODO Auto-generated method stub
						return false;
					}

					@Override
					public void setReadListener(ReadListener arg0) {
						// TODO Auto-generated method stub
						
					}
            };
             
            Map badIdea = HttpUtils.parsePostData(length, sin);
            
            //Object name = badIdea.get("name");
            
            //((Person)bean).setName(""+badIdea.get("name"));
 
            BeanUtils.populate(bean, badIdea);
             
            return bean;
         
        } catch(InstantiationException e) {
            throw new WebApplicationException(e);
        } catch (IllegalAccessException e) {
            throw new WebApplicationException(e);
        } catch (InvocationTargetException e) {
            throw new WebApplicationException(e);
        }
         
    }

	@Override
	public boolean isReadable(Class type, Type genericType,
			Annotation[] annotations, MediaType mediaType) {
		return true;
	} 
}